package com.example.easyutils.musicpage;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.easyutils.BaseActivity;
import com.example.easyutils.R;
import com.example.easyutils.httputil.HttpGetRequest;
import com.example.easyutils.util.MusicIdUtil;
import com.example.easyutils.util.MyTypeAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;


import net.qiujuer.genius.blur.StackBlur;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

import static android.view.View.GONE;

public class PlayMusicPage extends BaseActivity implements View.OnClickListener {
    public static String globalMusicId;
    public static Activity activity;
    private List songListAll;
    private String prePlayId = null;//上一首的id
    private ObjectAnimator objectAnimator;//声明ObjectAimator类
    private ImageView playImage,startPause,imageview1;
    private LinearLayout backgroundImage,speedLinear;
    private TextView musicDetail,videoProgress,sinner,fullTime,speedText,speedPointF,speedNormal,speedOnePointT
            ,speedOnePointF,speedTwo;
    private RelativeLayout ll_root;
    private float rotateDu = 0;
    private MediaPlayer mmediaPlayer = new MediaPlayer();
    private List listSong;
    private int num = 0;
    private String playUrlMedia;
    private static final int PLAY_MUSIC = 1,PLAY_URL = 2,PLAY_ERROR = 404;
    private Map singleSong;
    private SeekBar mSeekBar;
    private boolean hadDestroy = false;
    private int seekBarNum = 0;
    private View view;
    String musicId;

    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case PLAY_MUSIC:

                    Log.d("列表:",singleSong+"");
                    String singName = singleSong.get("name").toString();//歌名
                    String authName = ((Map)((List)singleSong.get("ar")).get(0)).get("name").toString();//歌手
                    String alia = singleSong.get("alia").toString();//原唱
                    String picUrl = ((Map)(singleSong.get("al"))).get("picUrl").toString();//图片
                    sinner.setText(authName+" >");
                    musicDetail.setText("《"+singName+"》"+"   "+alia);
                    Glide
                        .with(PlayMusicPage.this)
                        .load(picUrl)
                        .into(playImage);
//                    personal_bg.setBackgroundDrawable(result);
                    Drawable d=Drawable.createFromPath(picUrl);
//                    backgroundImage.setBackgroundDrawable(Drawable.createFromPath(picUrl));
                    BitmapUtil.returnBitMap(picUrl, new Handler(Looper.getMainLooper()){

                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);

                            // todo 具体逻辑
                            Bitmap mBitmap = (Bitmap) msg.obj;
                            Bitmap newBitmap = StackBlur.blur(mBitmap, 250, false);
                            imageview1.setImageBitmap(newBitmap);

                        }
                    });


                    break;
                case PLAY_URL:
                    if(mmediaPlayer != null){
                        mmediaPlayer.stop();
                    }
                    try {
                        mmediaPlayer.reset();
                        mmediaPlayer.setDataSource(playUrlMedia);

                        mmediaPlayer.prepare();

                        mmediaPlayer.start();

                        int currentTime = Math
                                .round(mmediaPlayer.getDuration() / 1000);
                        String currentStr = String.format("%s%02d:%02d","",
                                currentTime / 60, currentTime % 60);

                        fullTime.setText(currentStr);
                        Log.d("播放时长",mmediaPlayer.getDuration()+"");
                        startPause.setImageResource(R.drawable.bofang);

                        mSeekBar.setMax(mmediaPlayer.getDuration());
                        globalMusicId = musicId;
                        MusicIdUtil musicIdUtil = new MusicIdUtil();
                        musicIdUtil.setId(musicId);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    handler.postDelayed(runnable, 1000);

                    break;
                case PLAY_ERROR:
                    Toast.makeText(PlayMusicPage.this,"哎呀！没获取到！",Toast.LENGTH_SHORT).show();
                    break;


            }


        }
    };


    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if(!hadDestroy){

                handler.postDelayed(this,1000);
                int currentTime = Math
                        .round(mmediaPlayer.getCurrentPosition() / 1000);
                String currentStr = String.format("%s%02d:%02d","",
                        currentTime / 60, currentTime % 60);
                videoProgress.setText(currentStr);
//                Log.d("当前进度",mmediaPlayer.getCurrentPosition()+"");
                mSeekBar.setProgress(mmediaPlayer.getCurrentPosition());
            }
        }
    };

    private void setPlayerSpeed(float speed){//倍速播放
        if (android.os.Build.VERSION.SDK_INT >=
                android.os.Build.VERSION_CODES.M) {
            PlaybackParams playbackParams = mmediaPlayer.getPlaybackParams();
            playbackParams.setSpeed(speed);
            mmediaPlayer.setPlaybackParams(playbackParams);
        }
    }


//    @Override
//    protected void onWindowVisibilityChanged(int visibility) {
//        super.onWindowVisibilityChanged(visibility);
//        if (visibility == View.VISIBLE){
//            WLog.d("danxx" ,"可见");
//            //开始某些任务
//        }
//        else if(visibility == INVISIBLE || visibility == GONE){
//            WLog.d("danxx" ,"不可见");
//            //停止某些任务
//        }
//    }

    public void selectSpeed(View v){//选择倍速
        Log.d("倍速id",v.getId()+"");
        if(speedLinear.getVisibility()==speedLinear.VISIBLE){
            speedLinear.setVisibility(GONE);
        }else{
            speedLinear.setVisibility(View.VISIBLE);
        }
        OnTranslate();
    }

    /**
     * 位移
     *
     *
     */
    public void OnTranslate() {
        float width = ll_root.getWidth();//获取当前手机的的屏幕宽高
        objectAnimator = ObjectAnimator.ofFloat(speedLinear, "translationX", -width,-width/2,-width/3,-width/4,-width/9,width / 10,0);
        objectAnimator.setDuration(500);
        objectAnimator.start();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.play_music);
        activity = this;
        getMusicList();
//        songListAll
        ll_root = (RelativeLayout)findViewById(R.id.attri_root);
        playImage = (ImageView) findViewById(R.id.play_imageSource);
        startPause = (ImageView)findViewById(R.id.start_pause);
        musicDetail = (TextView)findViewById(R.id.top_title_scroll);
        videoProgress = (TextView)findViewById(R.id.video_time);
        mSeekBar = (SeekBar)findViewById(R.id.seekbar);
        sinner = (TextView)findViewById(R.id.sinner);
        fullTime = (TextView)findViewById(R.id.cur_time);
//        backgroundImage = (LinearLayout) findViewById(R.id.bg_img);
        imageview1 = (ImageView)findViewById(R.id.imageview1);
        speedLinear = (LinearLayout)findViewById(R.id.speedLinear);
        speedLinear.setVisibility(GONE);
        speedText = (TextView)findViewById(R.id.speed);
        speedPointF = (TextView)findViewById(R.id.speedPointF);
        speedNormal = (TextView)findViewById(R.id.speedNormal);
        speedOnePointT = (TextView)findViewById(R.id.speedOnePointT);
        speedOnePointF = (TextView)findViewById(R.id.speedOnePointF);
        speedTwo = (TextView)findViewById(R.id.speedTwo);
        musicDetail.setSelected(true);

        speedPointF.setOnClickListener(this);
        speedNormal.setOnClickListener(this);
        speedOnePointT.setOnClickListener(this);
        speedOnePointF.setOnClickListener(this);
        speedTwo.setOnClickListener(this);


        Intent intent = getIntent();
         musicId = intent.getStringExtra("musicId");
        playMusic(musicId);//播放单曲
        getMusicWord(musicId);//歌词
        Log.d("播放LIEBIAO ",musicId+"");
        Log.d("播放LIEBIAO11 ",mmediaPlayer.isPlaying()+"");

        OnRotate();

        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                seekBarNum = progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {//开始拖动

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {//结束拖动
                mmediaPlayer.seekTo(seekBarNum);
            }
        });

        mmediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {//播放完成
            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.d("shijian3",songListAll+"");
                if(songListAll!=null){
                    int randomNum = (int)(1+Math.random()*(songListAll.size()));
                    String id = ((Map)songListAll.get(randomNum)).get("id").toString();
                    prePlayId = id;
                    playMusic(id);
                    getMusicWord(id);//歌词
                    videoProgress.setText("");
                    mSeekBar.setProgress(0);
                }
            }
        });
//        mmediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//            @baiOverride
//            public void onCompletion(MediaPlayer mp) {
//                Log.d("tag", "播放完毕");
////根据需要添加自己的代du码。。。
//            }
//        });

    }


    @Override
    protected void onDestroy() {
        Log.d("销毁","onDestroy");
        super.onDestroy();
        if(mmediaPlayer != null){
            mmediaPlayer.stop();
            mmediaPlayer.release();
            hadDestroy = true;
        }
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            moveTaskToBack(false);
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    public void backPre(View v){//返回按钮
        Intent intent = new Intent();
        intent.setClass(PlayMusicPage.this, MusicMain.class);
        intent.putExtra("playMusicId",musicId);
//            FLAG_ACTIVITY_BROUGHT_TO_FRONT
//            FLAG_ACTIVITY_SINGLE_TOP
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);//设置不要刷新将要跳到的界面
        intent.putExtra("activityName","PlayMusicPage");
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//它可以关掉所要到的界面中间的activity
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d("返回键",keyCode+"");
        if(keyCode == KeyEvent.KEYCODE_BACK){
//            moveTaskToBack(true);
//
            Intent intent = new Intent();
            intent.setClass(PlayMusicPage.this, MusicMain.class);
            intent.putExtra("playMusicId",musicId);
//            FLAG_ACTIVITY_BROUGHT_TO_FRONT
//            FLAG_ACTIVITY_SINGLE_TOP
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);//设置不要刷新将要跳到的界面
            intent.putExtra("activityName","PlayMusicPage");
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//它可以关掉所要到的界面中间的activity
            startActivity(intent);
//            finish();

            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.d("页面3","不走create");
        super.onNewIntent(intent);
    }

    /**
     * 旋转
     *
     * @param
     */
    public void OnRotate() {
        objectAnimator = ObjectAnimator.ofFloat(playImage, "rotation", rotateDu, 360);
        objectAnimator.setDuration(8000);
        objectAnimator.setRepeatCount(100);//设置动画重复次数
        objectAnimator.setRepeatMode(ValueAnimator.RESTART);//动画重复模式
        //让旋转动画一直转，不停顿的重点
        objectAnimator.setInterpolator(new LinearInterpolator());
        objectAnimator.setRepeatCount(-1);
        objectAnimator.start();
    }


    public void paused(View v) throws IOException {//暂停  开始
        if(mmediaPlayer.isPlaying()){//正在播放
            mmediaPlayer.pause();
            startPause.setImageResource(R.drawable.zanting);
        }else{
            mmediaPlayer.start();
            startPause.setImageResource(R.drawable.bofang);
        }

    }

    public void nextOne(View v){//下一首
        if(mmediaPlayer != null){
            mmediaPlayer.stop();
        }
        Log.d("播放列表:",songListAll+"");
        int randomNum = (int)(1+Math.random()*(songListAll.size()));
        String id = ((Map)songListAll.get(randomNum)).get("id").toString();
        prePlayId = id;
        playMusic(id);
        getMusicWord(id);//歌词
        Log.d("播放单曲",id);
    }

    public void preOne(View v){//上一首
        if(mmediaPlayer != null){
            mmediaPlayer.stop();
        }
        Log.d("播放列表pre:",songListAll+"");
        int randomNum = (int)(1+Math.random()*(songListAll.size()));
        String id = ((Map)songListAll.get(randomNum)).get("id").toString();
        if(prePlayId == null){
            playMusic(id);
            getMusicWord(id);//歌词
        }else{
            playMusic(prePlayId);
            getMusicWord(prePlayId);//歌词
        }

        Log.d("播放单曲",id);
    }

    private void playMusic(final String id){//播放单曲
//        https://api.imjad.cn/cloudmusic/?type=detail&id=1460706496
        HttpGetRequest.sendOkHttpGetRequst("https://api.imjad.cn/cloudmusic/?type=detail&id="+id,
                new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(PLAY_ERROR);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String responseData = response.body().string();
                        Log.d("列表消息",responseData+"");
                        Gson gson = new GsonBuilder()
                                .registerTypeAdapter(new TypeToken<Map<String, List>>(){

                                }.getType(),new MyTypeAdapter()).create();
                        Map<String,List> dataDetail = gson.fromJson(responseData,new TypeToken<Map<String,List>>(){

                        }.getType());
                        Log.d("列表消息11",dataDetail.get("songs")+"");
                        singleSong = new HashMap();
                        singleSong = (Map) dataDetail.get("songs").get(0);
                        getPlaySrc(id);
                        handler.sendEmptyMessage(PLAY_MUSIC);
                    }
                });
    }

    private void getPlaySrc(String id){//单曲url
        Log.d("获取id",id);
        HttpGetRequest.sendOkHttpGetRequst("https://api.imjad.cn/cloudmusic/?type=details&id="+id,
                new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d("出错啦",e+"");
                        handler.sendEmptyMessage(PLAY_ERROR);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String responseData = response.body().string();
                        Log.d("列表消息22",responseData+"");
                        Gson gson = new GsonBuilder()
                                .registerTypeAdapter(new TypeToken<Map<String, List>>(){

                                }.getType(),new MyTypeAdapter()).create();
                        Map<String,List> dataDetail = gson.fromJson(responseData,new TypeToken<Map<String,List>>(){

                        }.getType());
                        Log.d("列表消息222",dataDetail.get("data")+"");
                        playUrlMedia = ((Map)dataDetail.get("data").get(0)).get("url").toString();
                        Log.d("列表消息222",playUrlMedia);
                        handler.sendEmptyMessage(PLAY_URL);

                    }
                });
    }

    private void getMusicWord(String id){//歌词
//        https://api.imjad.cn/cloudmusic/?type=lyric&id=

        HttpGetRequest.sendOkHttpGetRequst("https://api.imjad.cn/cloudmusic/?type=lyric&id="+id,
                new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d("出错啦",e+"");
                        handler.sendEmptyMessage(PLAY_ERROR);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String responseData = response.body().string();
                        Log.d("列表消息22",responseData+"");
                        Gson gson = new GsonBuilder()
                                .registerTypeAdapter(new TypeToken<Map<String, List>>(){

                                }.getType(),new MyTypeAdapter()).create();
                        Map<String,List> dataDetail = gson.fromJson(responseData,new TypeToken<Map<String,List>>(){

                        }.getType());
                        Log.d("列表消息222",dataDetail.get("tlyric")+"");
//                        playUrlMedia = ((Map)dataDetail.get("data").get(0)).get("url").toString();
//                        Log.d("列表消息222",playUrlMedia);
//                        handler.sendEmptyMessage(PLAY_URL);

                    }
                });
    }


        /**
        *
        *@param 
        *@author 19849
        *create at 2020/9/7 10:12
        */
    public void getMusicList(){
        
        HttpGetRequest.sendOkHttpGetRequst("https://api.imjad.cn/cloudmusic/?type=playlist&id=3779629",
                new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d("错误",e+"");
                        handler.sendEmptyMessage(PLAY_ERROR);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String dataMap = response.body().string();

                        Gson gson = new GsonBuilder()
                                .registerTypeAdapter(new TypeToken<Map<String, List>>(){

                                }.getType(),new MyTypeAdapter()).create();
                        Map<String,List> dataDetail = gson.fromJson(dataMap,new TypeToken<Map<String,List>>(){

                        }.getType());

                        List list = new ArrayList();
                        list = (List) ((Map)dataDetail.get("playlist")).get("trackIds");

//                        int randomNum = (int)(1+Math.random()*(list.size()));
                        songListAll = new ArrayList();//列表id
                        songListAll = list;
//                        Log.d("list的zhi:",list+"");
//                            getMusicSingle(list);
                    }
                });
    }

    
    /**
     * @description:    
     * @param:          
     * @return:         
     * @author:         19849
     * @time:           2020/9/7 11:12
     */
    @Override
    public void onClick(View v) {//
        speedLinear.setVisibility(GONE);
        switch (v.getId()){
            case R.id.speedPointF://0.5
                speedText.setText("0.5");
                setPlayerSpeed((float) 0.5);
                break;
            case R.id.speedNormal:
                speedText.setText("1.0");
                setPlayerSpeed((float) 1.0);
                break;
            case R.id.speedOnePointT:
                speedText.setText("1.25");
                setPlayerSpeed((float) 1.25);
                break;
            case R.id.speedOnePointF:
                speedText.setText("1.5");
                setPlayerSpeed((float) 1.5);
                break;
            case R.id.speedTwo:
                speedText.setText("2.0");
                setPlayerSpeed((float) 2.0);
                break;
        }
    }
}
